package com.googlecode.restitory.gae;

import java.util.Arrays;

public class BinaryContent extends Content {

	private byte[] value;

	public BinaryContent() {
		value = new byte[0];
	}

	public BinaryContent(byte[] array) {
		this.value = array;
	}

	public byte[] getValue() {
		return value;
	}

	public void setValue(byte[] value) {
		this.value = value;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + Arrays.hashCode(value);
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		BinaryContent other = (BinaryContent) obj;
		if (!Arrays.equals(value, other.value))
			return false;
		return true;
	}

	@Override
	public String toString() {
		StringBuilder ret = new StringBuilder(value.length * 3);
		for (byte b : value) {
			int num = (0xFF & b);
			if (num <= 0xF) {
				ret.append('0');
			}
			ret.append(Integer.toHexString(num));
		}
		return ret.toString();
	}

	public BinaryContent parse(String str) {
		if (str.length() % 2 != 0) {
			throw new RuntimeException("wrong length: " + str.length());
		}
		value = new byte[str.length() / 2];
		for (int i = 0; i < value.length; i ++) {
			int idx = i * 2;
			String d = str.substring(idx, idx + 2);
			byte b = (byte) Integer.parseInt(d, 16);
			value[i] = b;
		}
		return this;
	}
}
